package com.santiao.fuel;

/**
 * 启动页
 * <p>
 *
 *
 * @version 1.0
 */

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationSplashManager;

import com.santiao.publics.ad.TTAdManagerHolder;
import com.santiao.publics.ad.ads.MediationSplashService;
import com.santiao.publics.base.BaseActivity;
import com.santiao.publics.callback.DialogCallBack;
import com.santiao.publics.callback.OnResponseListener;
import com.santiao.publics.config.Const;
import com.santiao.publics.ui.AgreementDialog;
import com.santiao.publics.util.DeviceUtils;
import com.santiao.publics.util.HttpUtilSS;
import com.santiao.publics.util.LogUtil;
import com.santiao.publics.util.MyStringUtil;
import com.santiao.publics.util.SharedPreferencesUtil;
import com.santiao.publics.util.UmengUtil;
import com.santiao.publics.util.oaid.DemoHelper;
import com.santiao.publics.util.oaid.DemoHelperHuawei;
import com.santiao.publics.util.oaid.StringId;
import com.umeng.umcrash.UMCrash;
import com.yl.adsdk.YlLib;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class SplashActivity extends BaseActivity implements  DemoHelper.AppIdsUpdater, DemoHelperHuawei.AppIdsUpdater ,UmengUtil.AppIdsUpdater{

    // 启动APP后进入该页面进行预加载1.5S，之后跳转到首页


//    @BindView(R.id.splash_container)
//    FrameLayout splashContainer;
//    @BindView(R.id.root_layout)
//    RelativeLayout rootLayout;

    final Handler mHandler = new Handler();

    public  static int  sssssss=0;
    //-----------------------public公共------------s
    public static String mymanufacturer="" ;
    private int duration = 10000;
    public static DemoHelper demoHelper;


    public static String odid;
    public static String oaidYm;
    public static String oaidHw;
    public static String androidId;

    public static String mac = "";
    public static String imei = "";
    private CountDownTimer timer;

    public static Boolean intiAd = false;
    public static String packageName;
    public static int versionCode;
    public static String versionName;
    public String ecpm = "";
    public boolean ifloadAndShowSplashAd = true;
    public boolean onSplashLoadSuccess = false;

    public boolean onSplashAdShow = false;
    //是否跳过开屏
    public static boolean ifSplashActivity = true;
    public static Context context = null;
    public static Activity activity = null;

    private TTAdNative.CSJSplashAdListener mCSJSplashAdListener;
    private CSJSplashAd.SplashAdListener mCSJSplashInteractionListener;

//    private FrameLayout mSplashContainer;

    private CSJSplashAd mCsjSplashAd;
    public String slotId = "";
    public static MediationSplashManager manager;

    public String adStyle = "4";
    public static String userNo = null;
    String downloadChannel;
    UmengUtil umengUtil = null;
//    @Override
//    protected int getContentViewId() {
//        return R.layout.activity_splash;
//    }
//

    public static void gotoActivity(Intent intent) {


        context.startActivity(intent);

    }

//    @Override
//    protected void init(Bundle savedInstanceState) {
//
//    }

    private void loadAd() {

    }

    private void jumpToMain() {
        jumpToMain(0);
    }

    private void jumpToMain(long delayMillis) {
//        mHandler.postDelayed(() -> {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
//        }, delayMillis);
    }

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, SplashActivity.class);
        activity.startActivity(intent);
    }


    //-----------------------public公共------------e
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FuelApplication.ifMainActivity = true;
        SplashActivity.ifSplashActivity = true;
        setContentView(R.layout.public_activity_splash);

//        mSplashContainer = findViewById(R.id.fl_content);
        //---------------------public 公共需要
        if(!SharedPreferencesUtil.getStatus("sttttt")){
            SharedPreferencesUtil.saveStatus("sttttt",true);
        }else{

            sssssss=-1;
        }
        //初始化参数
        initp();
        if(SharedPreferencesUtil.getAgreementStatus()) {//隐私授权后每次登录
            updateConfigAd(this);//更新审核状态
        }
        onSplashAdShow = false;
        onSplashLoadSuccess = false;
        ifSplashActivity = true;
        context = this;
        activity = this;
        if (!SharedPreferencesUtil.getAgreementStatus()) {
            TextView textView = findViewById(R.id.tvTips);
            textView.setText("首次信息加载中,请稍后...");
        }else{
            TextView textView = findViewById(R.id.tvTips);
            textView.setText("信息加载中,请稍后...");
        }
        //友盟
        if (Const.IF_UM) {
            umengUtil =  new UmengUtil();
            umengUtil.initConfig(context);
        }




        //隐私提示框
        checkShowAgreementDialog();


        //initView(); //
//        mIsHandleScanner = getIntent().getBooleanExtra(Constant.SCANNER_MEDIA, false);

//
////  //       初始化 (授权)
//        requestPermissionLauncher = registerForActivityResult(
//                new ActivityResultContracts.RequestPermission(),
//                new ActivityResultCallback<Boolean>() {
//                    @Override
//                    public void onActivityResult(Boolean granted) {
//                        if (granted) {
//                            // 用户授予权限
//                            if (!mIsHandleScanner) {
//                                loadMusicData();
//                            }
//                        } else {
//                            // 用户拒绝权限
//                            againPermission(R.string.storage_permission);
//                        }
//                    }
//                }
//        );
//        initPermission();


    }

    public void  initp(){

        try {


            mymanufacturer = MyStringUtil.getmanufacturer(Build.MANUFACTURER);

            packageName = getPackageName();
            PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName, 0);
            versionName = packageInfo.versionName;
            versionCode = packageInfo.versionCode;

            HttpUtilSS.XUpUA = packageName+"/"+versionName;
        } catch (Exception e) {

            if (Const.IF_UM) {
                UMCrash.generateCustomLog(e, "packageName");
            }
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }






    //--------------------------------------------------public 公共需要


    // 隐私弹窗
    private void checkShowAgreementDialog() {
        if (!SharedPreferencesUtil.getAgreementStatus()) {
            AgreementDialog.showDialog(this, new DialogCallBack() {
                @Override
                public void buAgree() {
                    SharedPreferencesUtil.saveAgreementStatus(true);
                    initDatas("1");

//                    startMusicActivity("1");
                }

                @Override
                public void disagree() {
                    finish();
                }
            });
            return;
        } else {
            initDatas("2");
//            startMusicActivity("2");
        }


    }


    //更新后台配置
    public  static void updateConfigAd(Activity activity) {
        try {
            Map<String, String> map = getps();
            new Thread(new Runnable() {
                @Override
                public void run() {


                    String url = Const.URL_Q + "/dj-tools-api/app/v2/config";
                    HttpUtilSS.getRequestConfig(url, map, new OnResponseListener() {
                        @Override
                        public void onSuccess(String response) {
//                            intiAd = false;
                            boolean ifban = HttpUtilSS.updateConfigAdSet(url,response,mymanufacturer,map);
//                            if(activity!=null) {
//                                if (ifban) {
//                                    activity.finish();
//                                }
//                            }
                            intiAd();
                        }

                        @Override
                        public void onError(String responseBody, String error) {
                            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);
                            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD_2, false);
                            LogUtil.d(Const.TAG, url + "---err-------:" + map.toString() + "----------:" + responseBody + "----------:" + error);

                        }
                    });
                }
            }).start();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static Map<String, String> getps() {


        Map<String, String> map = new HashMap<>();
//        map.put("key", packageName);
        map.put("pkgName", packageName);
        map.put("version", Build.VERSION.RELEASE);
//        map.put("channel", Build.VERSION.RELEASE);
//
        map.put("appVersion", versionName);
        map.put("djId", SharedPreferencesUtil.getString("djId"));
//        map.put("zz", String.valueOf(System.currentTimeMillis()));
        return  map;
    }

    public Map<String, String> getp(){


        Map<String, String> map = new HashMap<>();
        map.put("key", packageName);
        map.put("pkgName", packageName);

        odid = SharedPreferencesUtil.getString("oaid");
        oaidHw = SharedPreferencesUtil.getString("oaidHw");
        oaidYm = SharedPreferencesUtil.getString("oaidYm");
        androidId = SharedPreferencesUtil.getString("androidId");
        mac = SharedPreferencesUtil.getString("mac");
        imei = SharedPreferencesUtil.getString("imei");
        map.put("oaId", odid);
        map.put("oaIdU", oaidYm);//友盟
        map.put("oaIdH", oaidHw);//华为
        map.put("imei", imei);
        map.put("mac", mac);
        map.put("androidId", androidId);
        map.put("appVersion", versionName);
//        map.put("dj_id", "ee1844b892c7ed5e");

        map.put("osVersion", Build.VERSION.RELEASE);
        map.put("deviceBrand", Build.MANUFACTURER);
        map.put("deviceModel", Build.MODEL);
//        map.put("deviceTag", MyStringUtil.getRiskInfo(this));

        try {
            map.put("deviceTag", YlLib.getRiskInfo(this));
        }catch (Exception e){
            e.printStackTrace();
        }
        try {//渠道
            downloadChannel= context.getString(R.string.downloadChannel);
            if(downloadChannel!=null && !downloadChannel.isEmpty()) {
                map.put("downloadChannel", downloadChannel);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("charge", DeviceUtils.isBatteryCharging(this) );//0:未充电、1:充电

        map.put("zz", String.valueOf(System.currentTimeMillis()));
        return  map;
    }
    boolean ifgetConfigAd = false;
    public void getConfigAd() {
        try {
            if(ifgetConfigAd){
                return;
            }else{
                ifgetConfigAd = true;
            }


            Map<String, String> map = getp();

            if (Const.ifAd) {//本地测试时


                SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);

            } else {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        String url = Const.URL_Q + "/dj-tools-api/app/v2/install";
                        HttpUtilSS.getRequest(url, map, new OnResponseListener() {
                            @Override
                            public void onSuccess(String response) {
//                                intiAd = false;
                                boolean ifban = HttpUtilSS.updateConfigAdSet(url,response,mymanufacturer,map);
//                                if(ifban){
//                                    finish();
//                                }

                                //初始化广告
                                intiAd();

                            }

                            @Override
                            public void onError(String responseBody, String error) {
                                LogUtil.d(Const.TAG, url + "---err-------:" + map.toString() + "----------:" + responseBody + "----------:" + error);
                                SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);

                            }
                        });


                    }
                }).start();
            }

        } catch (Exception e) {

            if (Const.IF_UM) {
                UMCrash.generateCustomLog(e, "installHttp");
            }
            e.printStackTrace();
            //ad标志
            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);

        }


    }

    private void initDatas(String type) {
        if (sssssss>0)
            return;
        if (sssssss==-1)
            type="2";
        else sssssss++;


        if ("1".equals(type)) {
            duration = duration + 2000;
//                adLoad = adLoad+5000;
            //缓存唯一标识
            try {
                StringId.idCache(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
//                if(odid == null || odid.isEmpty()) {
            //初始化获取oaid
            try {
                if(umengUtil!=null) {
                    umengUtil.getOaid(this,this);
                }
            }catch (Exception e){
                e.printStackTrace();
            }


            try {
                demoHelper = new DemoHelper(this, Const.lib);
                SplashActivity.demoHelper.getDeviceIds(this, true, false, false);
            }catch (Exception e){
                e.printStackTrace();
            }


            try {
                if("huawei".equals(SplashActivity.mymanufacturer)) {
                    new DemoHelperHuawei().getOaid(this, this);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
//                }

        }

        //初始化广告
//        intiAd();
        //友盟
        if (Const.IF_UM) {
            new UmengUtil().init(context);

        }

        ProgressBar pbProgress = findViewById(R.id.pbProgress);
        timer = new CountDownTimer(duration, 200) {
            int progress = 0;

            @Override
            public void onTick(long millisUntilFinished) {
                boolean ifAdBo = SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD);
                if(!ifAdBo){
                    ifAdBo = SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD_2);
                }

                float num = (duration - millisUntilFinished) / (float) duration * 100;
                LogUtil.i(Const.TAG, "initData------------" + duration + ":" + num + "--------sInitOk:" + TTAdManagerHolder.sInitOk + "-------------------------sInitSplashOk:" + TTAdManagerHolder.sInitSplashOk + "----------------ifAd:" + ifAdBo);
                progress = (int) num; // 每次增加指定的进度值
                pbProgress.setProgress(progress);

                if(userNo!=null){
                    TextView users =  findViewById(R.id.userNo);
                    users.setText("NO:"+userNo);
//                    users.setText("NO:"+downloadChannel);
                }

                if (ifAdBo && TTAdManagerHolder.sInitSplashOk) {
                    LogUtil.i(Const.TAG, "aaaaaaaaaaaaaaa------------" + duration + ":" + num + "----ifloadAndShowSplashAd：" + ifloadAndShowSplashAd +
                            "-----ifSplashActivity:" + ifSplashActivity + "----onSplashAdShow1:" + MediationSplashService.onSplashAdShow1 + "----onSplashAdShow2:" + MediationSplashService.onSplashAdShow2);

                    LogUtil.i(Const.TAG, "ccccccccccccccc------------" + duration + ":" + num + "------------ifSplashActivity:" + ifSplashActivity
                            + "(----onSplashAdShow2:" + MediationSplashService.onSplashAdShow2 + "---------------doubleShowOK1:" + MediationSplashService.doubleShowOK1 +
                            ")----(onSplashAdShow1:" + MediationSplashService.onSplashAdShow1 + "---------------doubleShowOK2:" + MediationSplashService.doubleShowOK2 + ")"
                            + "----(onSplashRenderSuccess1:+" + MediationSplashService.onSplashRenderSuccess1 + "----------onSplashRenderSuccess2:" + MediationSplashService.onSplashRenderSuccess2 + ")"

                    );

                    //                   TTAdManagerHolder.sInitSplashOk=false;
                    //授权后加载广告
                    //                    loadAuthorization();
                    // 加载并展示广告
                    if (ifloadAndShowSplashAd) {
                        ifloadAndShowSplashAd = false;
                        loadAndShowSplashAd();

                    } else if (

                            (num > 90 && ifSplashActivity && MediationSplashService.onSplashAdShow1 == false && MediationSplashService.onSplashAdShow2 == false)//超时没显示(9S)
                                    || (num > 80 && ifSplashActivity && MediationSplashService.onSplashRenderSuccess1 == false && MediationSplashService.onSplashRenderSuccess2 == false)//超时广告未初始化完成 （8s）


                    ) {
                        timer.cancel();
                        MainActivity.gotoActivity(SplashActivity.this);
                        LogUtil.i(Const.TAG, "MainActivity--11111111111111111111111111");
                        finish();

                    }
//                       else if(num>96 && ifSplashActivity
//
//                                 (
//
//                                         (MediationSplashService.onSplashAdShow2 &&  MediationSplashService.doubleShowOK1==true)//第二个插屏关闭（显示）后，调用了第一个差评显示逻辑
//
//                                         || (MediationSplashService.onSplashAdShow1 &&   MediationSplashService.doubleShowOK2==true) //第一个个插屏关闭（显示）后，调用了第二个差评显示逻辑
//                                 )
//                              ){//多插屏超时完毕
//
//
//
//                           GuideOptimizeActivity.gotoActivity(SplashActivity.this);
//
//                           LogUtil.i(Const.TAG,"GuideOptimizeActivity--33333333333333333333333333");
//                           finish();
//
//                       }
//                       else if (num > 98 && ifSplashActivity ) {//超时//如果显示开屏会自动跳过
//                           GuideOptimizeActivity.gotoActivity(SplashActivity.this);
//                           LogUtil.i(Const.TAG,"GuideOptimizeActivity--777777777");
//                           finish();
//                       }
                } else if ((num > 70 && !ifAdBo) //不加载广告
                        || (num > 80 && TTAdManagerHolder.sInitSplashOk == false)) {//超时、无AD
                    LogUtil.i(Const.TAG, "bbbbbbbbbbbbb------------" + duration + ":" + num + "--------sInitOk:" + TTAdManagerHolder.sInitOk + "-------------------------sInitSplashOk:" + TTAdManagerHolder.sInitSplashOk + "----------------ifAd:" + ifAdBo);

                    if (ifSplashActivity) {
                        timer.cancel();
                        MainActivity.gotoActivity(SplashActivity.this);
                        LogUtil.i(Const.TAG, "GuideOptimizeActivity--222222222222222222222222");
                        finish();
                        return;
                    }
                }
            }

            @Override
            public void onFinish() {
                pbProgress.setProgress(100);
                //                gotoNextActivity();
            }
        };
        timer.start();

    }

    public boolean ifOaid = false;
    public boolean ifOaidHw = false;
    public boolean ifOaidYm = false;
    @Override
    public void onIdsValid(String oaid, String vaid, String aaid) {
        Log.d(Const.TAG, "s---onIdsValid--------获取接口配置---oaid:" + oaid + "---vaid:" + vaid + "---aaid:" + aaid);
        ifOaid = true;

        oaidIfGetConfigAd();
        Log.d(Const.TAG, "e----onIdsValid-------获取接口配置");
    }

    @Override
    public void onIdsValid(String oaid) {//华为
        Log.d(Const.TAG, "s---onIdsValid--hw------获取接口配置---oaid:" + oaid );
        ifOaidHw=true;
        oaidIfGetConfigAd();
        Log.d(Const.TAG, "e----onIdsValid--hw-----获取接口配置");
    }

    @Override
    public void onIdsValidUm(String oaid) {//友盟
        Log.d(Const.TAG, "s---onIdsValid--um------获取接口配置---oaid:" + oaid );
        ifOaidYm = true;
        oaidIfGetConfigAd();
        Log.d(Const.TAG, "e----onIdsValid--um-----获取接口配置");
    }

    public int oaidIfGetConfigAdCount=0;
    public void  oaidIfGetConfigAd(){
        oaidIfGetConfigAdCount ++;
        if("huawei".equals(mymanufacturer)){//华为需要三个oaid
            if(ifOaid && ifOaidHw && ifOaidYm){
                //获取接口配置
                getConfigAd();

            }else if(oaidIfGetConfigAdCount==1){
                configAdJob();
            }


        }else{
            if(ifOaid &&  ifOaidYm){
                getConfigAd();
            }else if(oaidIfGetConfigAdCount==1){
                configAdJob();
            }



        }

    }

    public void configAdJob(){
//        CountDownTimer timer = new CountDownTimer(1000, 200) {
//            @Override
//            public void onTick(long l) {
//            }
//
//            @Override
//            public void onFinish() {
//                getConfigAd();
//            }
//        };
//        timer.start();

        try {


            Handler handler = new Handler(Looper.getMainLooper());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getConfigAd();
                }
            }, 1000);

        }catch (Exception e){
            e.printStackTrace();
            getConfigAd();
        }
    }


    private void loadAndShowSplashAd() {

        MediationSplashService mediationSplashService = new MediationSplashService();
        mediationSplashService.intiDate(context, activity, findViewById(R.id.fl_content), getResources().getString(R.string.splash_media_id), getResources().getString(R.string.splash_media_id_s), findViewById(R.id.fl_content), getResources().getString(R.string.splash_media_2_id), getResources().getString(R.string.splash_media_2_id_s));

    }


    private void startMusicActivity(String type) {

        LogUtil.i(Const.TAG, "startMainActivity--" + type);
//        startActivity(new Intent(this, MusicActivity.class));


        MainActivity.gotoActivity(context);


        finish();
    }



    public static void intiAd() {


        if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD) || SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD_2)) {


            if (!intiAd) {
                intiAd = true;
                //穿山甲SDK初始化
                //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现context为null的异常
                TTAdManagerHolder.init(context);
                TTAdManagerHolder.start(context);

                //--------------adspark
                //           上报事件初始化
                if (Const.IF_ADSPARK) {
                    //                    InitConfig config = new AdSparkUtils().initConfig(context, activity);

                } else {
                    //                    new GravityUtils().initConfig(context);
                }


//                //友盟
//                if (Const.IF_UM) {
//                    new UmengUtil().init(context);
//
//                }
            }
        }

    }
}



